var app=getApp();
var ux = require('../../../../lib/ux.js');
var WxParse = require('../../../../utils/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {    
    a: 0,
      b: 0,
    c: 0,
      d:0,
    sum: 0,
    prices:0,
    merchant: {},
    entity:{},
    optinoss:[],
    hig:[],
    attribute:"",
    isShow:true,
    count:1,
    images:[],
    isYqUrl:'',
    saveUrl:'/api/memberShop/jiaRuCar.do',
    action:"/api/memberShop/goodsDetail.do",
	submit:"{{submit}}"
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    var scene = decodeURIComponent(options.scene)
    if (scene && scene != undefined && scene != "undefined") {
      var scenes = scene.split("_");
      this.setData({
        id: scenes[0],
        banrdId: scenes[1],
        sum: scenes[2],
        prices: scenes[2],
      })
      wx.login({
        success: function (res) {
          if (res.code) {
            var jscode = res.code;
            //发起网络请求
            ux.request("/api/member/isLogin.do", {
              jscode: jscode
            }, function (protocol) {
                wx.setStorageSync("token", protocol.data.token);
                wx.setStorageSync("userInfo", protocol.data.userInfo);
                wx.setStorageSync("setting", protocol.data.setting);
            }, true);
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        },
        complete: function (res) {
          console.log(JSON.stringify(res))
        }
      })
    }else{
      this.setData({
        id: options.id
      })
      if(options.prices){
        this.setData({
          sum: options.prices,
          prices: options.prices,
          id: options.id
        })
      }
        if(options.fx){
          if (options.fx==1) {
          wx.login({
            success: function (res) {
              if (res.code) {
                var jscode = res.code;
                //发起网络请求
                ux.request("/api/member/isLogin.do", {
                  otherId:options.userId,
                  banrdId:options.banrdId,
                  jscode: jscode
                }, function (protocol) {
                  if (protocol.data.type == 1) {
                    wx.setStorageSync("token", protocol.data.token);
                    wx.setStorageSync("userInfo", protocol.data.userInfo);
                    wx.setStorageSync("setting", protocol.data.setting);
                  } else if (protocol.data.type == 2) {
                    wx.reLaunch({
                      url: '/pages/auth?type=1',
                    })
                  }
                }, true);
              } else {
                console.log('登录失败！' + res.errMsg)
              }
            },
            complete: function (res) {
              console.log(JSON.stringify(res))
            }
          })
        }
        }
    }
    
  },
  
  onForm:function(event){
	if(this.data.submit){
		  var $this = this;
		  var dataset = event.currentTarget.dataset;
		  ux.request(this.data.submit,detail.value,function(protocol){
				if(protocol.success){
					if(dataset.url){
						wx.redirectTo(dataset.url);
					}
				}
		  },true);
	 }
  },
  
  onTap:function(event){
	  var dataset = event.currentTarget.dataset;
	  var data = this.data;
	  if(dataset.key && dataset.val){
		  data[dataset.key] = dataset.val;
	  }
	  this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.isShow){
          this.setData({
            isShow:false
          })
      var $this = this;
      var parmas={id:this.data.id}
      wx.showLoading({
        title: '加载中...',
        mask:true
      })
      ux.request(this.data.action, parmas, function (protocol) {
        console.log(JSON.stringify(protocol.data));
        wx.hideLoading();
        $this.setData({
          entity: protocol.data.entity,
          hig: protocol.data.hig,
          optinoss: JSON.parse(protocol.data.entity.options),
          agentType: protocol.data.agentType,
          images: $this.data.images.concat(protocol.data.entity.shufs.split(","))
        });
       
        if ($this.data.prices==0){
          $this.setData({
            sum: protocol.data.entity.price
          })
        }
          ux.request("/api/memberShop/getDetailParams.do",{banrdId:protocol.data.entity.merchant},function(atad){
           wx.hideLoading();
            var pam = atad.data.pam;
            $this.setData({
              a: ux.acMul(pam.pPtJj, $this.data.prices),
              b: ux.acMul(pam.pPtZj, $this.data.prices),
              c: ux.acMul(pam.pDlZj, $this.data.prices),
              d: ux.acMul(pam.pDlJj, $this.data.prices),
             merchant: atad.data.merchant,
              pam: pam
           });
         },true);

       
        WxParse.wxParse('articleDetail', 'html', protocol.data.entity.descr, $this);
      });
   }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  this.setData({
    isShow:true
  })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this;
    wx.showShareMenu({
      withShareTicket: true
    })
    var userInfo = wx.getStorageSync("userInfo");
    var obj = this.data.entity;
    var shareObj = {
      title: wx.getStorageSync("setting").coverTitle,
      imageUrl: wx.getStorageSync("setting").coverImg,
      path: '/pages/member/tab1/shop/detail?fx=1&userId=' + userInfo.uid + "&id=" + obj.id + "&banrdId=" + obj.merchant + '&prices=' + $this.data.prices,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          that.toast("转发成功");
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          that.toast("取消转发");
        } else if (res.errMsg == 'shareAppMessage:fail') {
          that.toast("转发失败");
        }

      }
    }
    return shareObj;
  },
  eddCount:function(){
    if (this.data.count == 1){
    return false;
   }else{
     this.setData({
       count: this.data.count-1,
       sum: ux.acSub(this.data.sum, this.data.prices)
     })
   }
  },
  addCount:function(){
    this.setData({
      count: this.data.count + 1,
      sum: ux.acAdd(this.data.sum, this.data.prices)
    })
  },
  gotoChongZhi:function(){
    
    wx.navigateTo({
      url: '/pages/member/tab3/recharge/recharge?id=' + this.data.entity.id+'&tab=1',
    })
  },
  gotoApply:function(){//去代理申请页面
     wx.navigateTo({
       url: '/pages/member/tab1/agent/applyAgent?id=' + this.data.entity.merchant,
     })
  },
  selectObtion: function (event) {//选择属性
    var dataset = event.currentTarget.dataset;
    var aindex = dataset.aindex;
    var bindex = dataset.bindex;
    var optins = this.data.optinoss; 


    var parent = optins[aindex].childs;
    for (var i = 0; i < parent.length; i++) {
      if (bindex == i) {
        parent[i].desp = "select";
      } else {
        parent[i].desp = 1;
      }
    }
    var ops = this.data.optinoss;
    ops[aindex].child = parent;
    var arra = ops;
    var property = "";
    for (var i = 0; i < arra.length; i++) {
      for (var j = 0; j < arra[i].child.length; j++) {
        if (arra[i].child[j].desp == "select") {
          property = property + arra[i].child[j].name + " "
        }
      }
    }
 
    this.setData({
      attribute: property,
      optinoss: ops
    })
  },
  jiaruGouwuche:function(){
    var self=this;
    // if (this.data.optinoss){
    //   if (!this.panduan(this.data.optinoss)) {
    //     this.toast("请选择规格属性");
    //     return false;
    //   }
    // }
    
    var pamars = {
      id: this.data.id,
      count: this.data.count,
      price: this.data.prices,
      atrebuite: this.data.attribute
    }
    if (this.data.attribute) {
      pamars.atrebuite = this.data.attribute;
    } else {
      pamars.atrebuite = "未选择";
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    ux.request(this.data.saveUrl, pamars, function (protocol) {
      wx.hideLoading();
      self.toast("提交成功");
      wx.switchTab({
        url: '/pages/member/tab2/car',
      })
    }, true)
  },
  panduan: function (optinoss){
      var isDk=true;
      console.log(optinoss);
    for (var i = 0; i < optinoss.length; i++) {
      var isflag=false;
      for (var j = 0; j < optinoss[i].child.length; j++) {
        if (optinoss[i].child[j].desp == "select") {
          isflag=true;
          break;
        }
      }
      if (!isflag){
        isDk=false;
        break;
      }
    }
    return isDk;
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  tel: function () {
    var self = this;
    console.log("打电话" + self.data.merchant.contactNumber)
    wx.makePhoneCall({
      phoneNumber: self.data.merchant.contactNumber,
    })
  },
  backHome:function(){
    wx.reLaunch({
      url: '/pages/member/tab1/sugarSpice?id=' + this.data.entity.merchant,
    })
  }
})
